package hzmg.akkacloud.server.web.controller;

import com.hzmg.akkacloud.common.response.ResultDTO;
import hzmg.akkacloud.server.core.service.ConfigService;
import hzmg.akkacloud.server.persistence.PageResult;
import hzmg.akkacloud.server.persistence.remote.model.ConfigInfoDO;
import hzmg.akkacloud.server.persistence.remote.repository.ConfigInfoRepository;
import hzmg.akkacloud.server.web.request.ConfigInfoListRequest;
import hzmg.akkacloud.server.web.request.ModifyConfigInfoRequest;
import hzmg.akkacloud.server.web.response.ConfigInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/config")
@Slf4j
public class ConfigInfoController {

    @Resource
    private ConfigService configService;

    @Resource
    private ConfigInfoRepository configInfoRepository;

    @PostMapping("/create")
    public ResultDTO create(@RequestBody ModifyConfigInfoRequest modifyConfigInfoRequest){
        ConfigInfoDO configInfoDO = new ConfigInfoDO();
        BeanUtils.copyProperties(modifyConfigInfoRequest, configInfoDO);
        configService.create(configInfoDO);
        return ResultDTO.success(null);
    }

    @PostMapping("/list")
    public ResultDTO<PageResult<ConfigInfoVO>> list(@RequestBody ConfigInfoListRequest configInfoListRequest) {

        Pageable limit = PageRequest.of(configInfoListRequest.getPageNum(), configInfoListRequest.getPageSize());
        Page<ConfigInfoDO> configPage;
        if (StringUtils.isEmpty(configInfoListRequest.getSrcUser())){
//            throw new AkkaCloudException("用户未登录！");
            return ResultDTO.failed("用户未登录！");
        }else {
            configPage = configInfoRepository.findBySrcUser(configInfoListRequest.getSrcUser(), limit);
        }
        return ResultDTO.success(convert(configPage));
    }

    private PageResult<ConfigInfoVO> convert(Page<ConfigInfoDO> data) {
        PageResult<ConfigInfoVO> newPage = new PageResult<>(data);
        newPage.setData(data.getContent().stream().map(configInfoVO -> ConfigInfoVO.from(configInfoVO)).collect(Collectors.toList()));
        return newPage;
    }


}
